package org.ran.demo.http.http;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

import org.ran.demo.http.util.FileUtil;
import org.ran.demo.http.util.StreamUtil;

public class SaveResponseClinet {
    public static void main(String[] args) throws Exception{
        try(Socket socket = new Socket();){
            socket.connect(new InetSocketAddress("127.0.0.1", 8080));
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            List<String> lines = Files.readAllLines(Paths.get(FileUtil.REQUEST_LOCATION));
            for (String line : lines) {
                StreamUtil.writeLine(line, out);
            }
            int length = 0;
            lines = new ArrayList<>();
            while (true) {
                String res = StreamUtil.readLine(in);
                lines.add(res);
                if (res.isEmpty()) {
                    break;
                }
                String[] header = res.split(":");
                if (header[0].equals("Content-Length")) {
                    length = Integer.parseInt(header[1].trim());
                }
            }
            byte[] body = StreamUtil.readLength(in, length);
            Files.write(Paths.get(FileUtil.RESPONSE_HEADER), lines, StandardOpenOption.CREATE_NEW);
            Files.write(Paths.get(FileUtil.RESPONSE_BODY), body, StandardOpenOption.CREATE_NEW);
        }
    }
}
